<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

</body>
<script>
let depts = [
    {id: 1,name:'节点1', pid: ''},
    {id: 11,name:'节点1-1', pid: 1},
    {id: 12,name:'节点1-2', pid: 1},
    {id: 121,name:'节点1-2-1', pid: 12},
    {id: 2,name:'节点2', pid: ''}
]
/*==============================⭐ 法一 ==============================*/
// 1 找孩子，添加chrildren字段
// depts.forEach(t=>{
//     let children = depts.filter(m=>m.pid === t.id)
//     if(children.length>0){
//         t.children = children
//     }
// })

// 2 返回最外层节点
// let list = depts.filter(t=>t.pid==='')
// console.log(list)

/*==============================⭐ 法二 ==============================*/
// 递归函数：自己调用自己
function Fn(arr,pid){
    let result = arr.filter(t=>t.pid === pid)
    result.forEach(t=>{
        let children = Fn(arr,t.id)
        if(children.length>0){
            t.children=children
        }
    })
    // console.log(result)

    return result
}
// 返回最外层节点
console.log(Fn(depts,''))

</script>
</html>
